package com.s7.recycler.helper;

import android.graphics.Color;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.s7.recycler.adapter.BaseLoadingAdapter;
import com.s7.recycler.listener.OnLoadDataListener;
import com.s7.recycler.listener.OnLoadingListener;
import com.s7.recycler.listener.Recycler;

import java.util.List;

/**
 * Created by Administor on 2018\7\6 0006.
 * RecyclerView 上拉加载下拉刷新事件
 * 兼容Grid布局、Linear布局、StaggeredGrid布局（支持布局切换）
 */
public class LoadingHelper<T> implements SwipeRefreshLayout.OnRefreshListener, OnLoadingListener {
    /**
     * adapter 存在的标志
     */
    private boolean hasInitAdapter = false;

    /**
     * 页码
     */
    private int page = 1;
    private int pageSize;

    private boolean isAadditional = true;
    private SwipeRefreshLayout mSwipeRefresh;
    private RecyclerView mRecycler;
    private RecyclerView.LayoutManager mManager;
    private RecyclerView.ItemDecoration mDecoration;
    private BaseLoadingAdapter<T> mAdapter;
    private Recycler.OnCheckedChangeListener<T> mCheckedChange;
    private Recycler.OnClickListener<T> mClick;
    private Recycler.OnItemClickListener<T> mItemClick;
    private Recycler.OnItemLongClickListener<T> mItemLongClick;
    private OnLoadDataListener mLoadData;

    /**
     * 是否在加载中
     */
    private boolean isLoad = false;

    /**
     * 设置是否显示附加页
     * @param aadditional
     */
    public LoadingHelper setAadditional(boolean aadditional) {
        isAadditional = aadditional;
        return this;
    }

    public LoadingHelper setPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }

    /**
     * 设置 SwipeRefreshLayout
     * @param mSwipeRefresh
     */
    protected LoadingHelper setSwipeRefresh(SwipeRefreshLayout mSwipeRefresh) {
        this.mSwipeRefresh = mSwipeRefresh;
        return this;
    }

    /**
     * 设置RecyclerView
     * @param mRecycler
     */
    protected LoadingHelper setRecycler(RecyclerView mRecycler) {
        this.mRecycler = mRecycler;
        return this;
    }

    /**
     * 设置布局方式
     * @param mManager
     * @return
     */
    public LoadingHelper setManager(RecyclerView.LayoutManager mManager) {
        this.mManager = mManager;
        return this;
    }

    /**
     * 设置分割线
     * @param mDecoration
     * @return
     */
    public LoadingHelper setDecoration(RecyclerView.ItemDecoration mDecoration) {
        this.mDecoration = mDecoration;
        return this;
    }

    /**
     * 设置Adapter
     * @param mAdapter
     */
    protected LoadingHelper setAdapter(BaseLoadingAdapter<T> mAdapter) {
        this.mAdapter = mAdapter;
        return this;
    }

    protected LoadingHelper setLoadData(OnLoadDataListener mLoadData) {
        this.mLoadData = mLoadData;
        return this;
    }

    public LoadingHelper setCheckedChange(Recycler.OnCheckedChangeListener<T> mCheckedChange) {
        this.mCheckedChange = mCheckedChange;
        return this;
    }

    protected LoadingHelper setClick(Recycler.OnClickListener<T> mClick) {
        this.mClick = mClick;
        return this;
    }

    protected LoadingHelper setItemClick(Recycler.OnItemClickListener<T> mItemClick) {
        this.mItemClick = mItemClick;
        return this;
    }

    protected LoadingHelper setItemLongClick(Recycler.OnItemLongClickListener<T> mItemLongClick) {
        this.mItemLongClick = mItemLongClick;
        return this;
    }

    /**
     * 初始化数据
     */
    public void initAdapter(){
        if (mAdapter == null || mRecycler == null || mManager == null) {
            return;
        }
        if(mSwipeRefresh != null && mLoadData != null) {
            mSwipeRefresh.setOnRefreshListener(this);
        }

        onManager();

        if (mDecoration != null) {
            mRecycler.addItemDecoration(mDecoration);
        }

        mAdapter.setAadditional(isAadditional)
                .setPageSize(pageSize)
                .setCheckedChange(mCheckedChange)
                .setClick(mClick)
                .setItemClick(mItemClick)
                .setItemLongClick(mItemLongClick);
        if (mLoadData != null) {
            mAdapter.setLoadingListener(this);
        }
        mRecycler.setAdapter(mAdapter);
        hasInitAdapter = true;
    }

    /**
     * 瀑布流布局管理器处理
     */
    private void onManager() {
        if (mManager instanceof StaggeredGridLayoutManager) {
            ((StaggeredGridLayoutManager) mManager)
                    .setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        }
        mRecycler.setLayoutManager(mManager);
        mRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mManager instanceof StaggeredGridLayoutManager) {
                    //防止第一行到顶部有空白区域
                    ((StaggeredGridLayoutManager) mManager).invalidateSpanAssignments();
                }
            }
        });
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        if (isLoad()) {
            return;
        }
        page = 1;
        isLoad = true;
        mLoadData.onLoadData(page);
    }

    @Override
    public void onReload() {
    }

    /**
     * 加载更多/再试一次
     */
    @Override
    public void onLoading() {
        if (isLoad()) {
            return;
        }
        isLoad = true;
        mLoadData.onLoadData(page);
    }

    /**
     * 设置刷新动画
     * @param flag
     */
    private void setSwipeRefresh(boolean flag) {
        if (mSwipeRefresh != null) {
            if (flag) {
                if (!mSwipeRefresh.isRefreshing()) {
                    mSwipeRefresh.setRefreshing(true);
                }
            } else {
                if (mSwipeRefresh.isRefreshing()) {
                    mSwipeRefresh.setRefreshing(false);
                }
            }
        }
    }

    /**
     * 是否在执行加载动作（刷新/加载更多）
     * @return
     */
    private boolean isLoad() {
        if (isLoad) {
            setSwipeRefresh(false);
        }
        return isLoad;
    }

    /**
     * 切换RecyclerView 布局管理
     * @param layoutManager
     */
    public void setLayoutManager(final RecyclerView.LayoutManager layoutManager) {
        if (mRecycler != null && mAdapter != null && layoutManager != null) {
            mManager = layoutManager;
            onManager();
            mAdapter.onAttachedToRecyclerView(mRecycler);
            notifyAdapter();
        }
    }

    /**
     * 回到第一页
     */
    public void loadFirstPage() {
        page = 1;
        if(!hasInitAdapter){
            initAdapter();
        }
        if (mLoadData != null) {
            setSwipeRefresh(true);
            mLoadData.onLoadData(page);
            isLoad = true;
        }
    }

    /**
     * 网络连接失败
     */
    public void notifyError() {
        isLoad = false;
        mAdapter.setLoadError(true);
    }

    /**
     * 首次加载没有数据
     */
    public void notifyNull() {
        if (page == 1) {
            isLoad = false;
            setSwipeRefresh(false);
            mAdapter.setNull(true);
        }
    }

    /**
     * 刷新Adapter
     * @param datas
     */
    public void notifyAdapter(List<T> datas) {
        if (page == 1) {
            setSwipeRefresh(false);
            mAdapter.onRefresh(datas);
        } else {
            mAdapter.add(datas);
        }
        isLoad = false;
        page++;
    }

    /**
     * 刷新Adapter
     * @param data
     */
    public void notifyAdapter(T data) {
        mAdapter.add(data);
    }

    /**
     * 刷新Adapter
     */
    public void notifyAdapter() {
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 刷新所有数据
     * @param datas
     */
    public void notifyRefresh(List<T> datas) {
        mAdapter.onRefresh(datas);
    }

    /**
     * 替换指定位置数据
     * @param position
     * @param data
     */
    public void notifyReplace(int position, T data) {
        mAdapter.replace(position, data);
    }

    /**
     * 删除指定位置的内容
     * @param position
     */
    public void notifyRemove(int position) {
        mAdapter.remove(position);
    }

    /**
     * 获取所有数据
     * @return
     */
    public List<T> getData() {
        return mAdapter.getDatas();
    }

    public static class Builder<T> {
        private SwipeRefreshLayout mSwipeRefresh;
        private RecyclerView mRecycler;
        private RecyclerView.LayoutManager mManager;
        private RecyclerView.ItemDecoration mDecoration;
        private BaseLoadingAdapter<T> mAdapter;
        private Recycler.OnCheckedChangeListener<T> mCheckedChange;
        private Recycler.OnClickListener<T> mClick;
        private Recycler.OnItemClickListener<T> mItemClick;
        private Recycler.OnItemLongClickListener<T> mItemLongClick;
        private OnLoadDataListener mLoadData;
        private boolean isAadditional = true;
        private int pageSize = 10;

        /**
         * 设置是否显示附加页
         * @param isAadditional
         * @return
         */
        public Builder setAadditional(boolean isAadditional) {
            this.isAadditional = isAadditional;
            return this;
        }

        public Builder setPageSize(int pageSize) {
            this.pageSize = pageSize;
            return this;
        }

        public Builder setSwipeRefresh(SwipeRefreshLayout mSwipeRefresh) {
            return setSwipeRefresh(mSwipeRefresh, Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN);
        }

        public Builder setSwipeRefresh(SwipeRefreshLayout mSwipeRefresh, int... colors) {
            this.mSwipeRefresh = mSwipeRefresh;
            this.mSwipeRefresh.setColorSchemeColors(colors);
            return this;
        }

        public Builder setRecycler(RecyclerView mRecycler, final RecyclerView.LayoutManager mManager) {
            return setRecycler(mRecycler, mManager, null);
        }

        public Builder setRecycler(RecyclerView mRecycler, final RecyclerView.LayoutManager mManager,
                                   RecyclerView.ItemDecoration mDecoration) {
            this.mRecycler = mRecycler;
            this.mManager = mManager;
            this.mDecoration = mDecoration;
            return this;
        }

        public Builder setAdapter(BaseLoadingAdapter<T> mAdapter) {
            return setAdapter(mAdapter, false);
        }

        /**
         * 设置Adapter的底部是否显示
         * @param mAdapter
         * @param isFooter
         * @return
         */
        public Builder setAdapter(BaseLoadingAdapter<T> mAdapter, boolean isFooter) {
            return setAdapter(mAdapter, isFooter, false);
        }

        /**
         * 设置Adapter的底部是否显示
         * @param mAdapter
         * @param isLoad
         * @param isFooter
         * @return
         */
        public Builder setAdapter(BaseLoadingAdapter<T> mAdapter, boolean isLoad, boolean isFooter) {
            this.mAdapter = mAdapter;
            this.mAdapter.showLoad(isLoad).showFooter(isFooter);
            return this;
        }

        public Builder setLoadData(OnLoadDataListener mLoadData) {
            this.mLoadData = mLoadData;
            return this;
        }

        public Builder setCheckedChange(Recycler.OnCheckedChangeListener<T> mCheckedChange) {
            this.mCheckedChange = mCheckedChange;
            return this;
        }

        public Builder setClick(Recycler.OnClickListener<T> mClick) {
            this.mClick = mClick;
            return this;
        }

        public Builder setItemClick(Recycler.OnItemClickListener<T> mItemClick) {
            this.mItemClick = mItemClick;
            return this;
        }

        public Builder setItemLongClick(Recycler.OnItemLongClickListener<T> mItemLongClick) {
            this.mItemLongClick = mItemLongClick;
            return this;
        }

        public <T> LoadingHelper<T> build() {
            LoadingHelper mHelper = new LoadingHelper<T>()
                    .setPageSize(pageSize)
                    .setAadditional(isAadditional)
                    .setSwipeRefresh(mSwipeRefresh)
                    .setRecycler(mRecycler)
                    .setManager(mManager)
                    .setDecoration(mDecoration)
                    .setAdapter(mAdapter)
                    .setCheckedChange(mCheckedChange)
                    .setClick(mClick)
                    .setItemClick(mItemClick)
                    .setItemLongClick(mItemLongClick)
                    .setLoadData(mLoadData);
            mHelper.initAdapter();
            return mHelper;
        }
    }
}
